const express = require('express')
const router = express()
const util =require('../../util/acfunutil') ;
var AV = require('leanengine');
var Article = AV.Object.extend('Article');

router.get('/', (req, res) => {
    const pageNo = req.query.pageNo||1;
    const sort = req.query.sort||4;
    const channelIds = req.query.channelIds||110;
    const pageSize = req.query.pageSize||20;
    const  headers = util.buildApiHeader();
    util.service.get(util.CDN_API+`/searches/channel?sort=${sort}&pageNo=${pageNo}&pageSize=${pageSize}&recommendSize=6&channelIds=${channelIds}`,{headers}).then(resp=>{
        res.send(resp.data)
    }).catch(err=>{
        res.send({code:500,message:err.message})
    })
})

router.get('/:id', (req, res) => {
    const  headers = util.buildApiHeader();
    if(req.header('host').indexOf('gakki')>=0){
        util.service.get(util.CDN_API+ `/contents/${req.params.id}`,{headers}).then(resp=>{
            res.send(resp.data)
        })
    }else {
        var query = new AV.Query(Article);
        query.equalTo('contentId',parseInt(req.params.id))
        query.find().then(function (results) {
            if(results.length>0){
                res.send({code:200,message:'OK',data:results[0]});
            }else {
                util.service.get(util.CDN_API+ `/contents/${req.params.id}`,{headers}).then(resp=>{
                    const data = resp.data.data;
                    if(data.isArticle === 1){
                        var content = new Article();
                        for(let key in data){
                            if(key !== 'updatedAt'){
                                content.set(key, data[key]);
                            }
                        }
                        content.save().then(content => {
                            // 成功保存之后，执行其他逻辑.
                            res.send(resp.data)
                        }, error => {
                            // 异常处理
                            console.error('Failed to create new object, with error message: ' + error.message);
                        });
                    }

                }).catch(err=>{
                    res.send({code:500,message:err.message})
                })
            }
        }, function (error) {
            res.send({code:500,message:error.message})
        });
    }


})

router.get('/:id/comments', (req, res) => {
    const  headers = util.buildAcfunHeader();
    const pageNo = req.query.pageNo||1;
    if (req.params.id == 'undefined') {
        res.send({code:400,message:'param not correct'})
    } else {
        util.service.get(util.ACFUN_API+ `/comment/content/web/list?contentId=${req.params.id}&pageNo=${pageNo}&pageSize=30&cd=1&name=sanae`,{headers}).then(resp=>{
            res.send(resp.data)
        }).catch(err=>{
            res.send({code:500,message:err.message})
        })
    }
})

module.exports = router
